package cn.xiaoyu.su.util;

import cn.xiaoyu.su.model.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * @author sufs
 * @date 2022/10/28 17:25
 */
@Slf4j
public class JWTUtil {

    /**
     * 主题
     */
    private static final String SUBJECT = "xiaoyu";

    /**
     * 加密密钥
     */
    private static final String SECRET = "xiaoyu.2019";

    /**
     * 令牌前缀
     */
    private static final String TOKEN_PREFIX = "dcloud-link";

    /**
     * token过期时间
     */
    private static final long EXPIRED = 1000*60*60*24*7l;

    /**
     * 根据用户信息生成令牌
     * @param loginUser
     * @return
     */
    public static String geneJsonWebToken(LoginUser loginUser) {
        if (loginUser == null) {
            throw new NullPointerException("对象为空");
        }

        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("head_img",loginUser.getHeadImg())
                .claim("account_no",loginUser.getAccountNo())
                .claim("username",loginUser.getUsername())
                .claim("auth",loginUser.getAuth())
                .claim("phone",loginUser.getPhone())
                .claim("mail",loginUser.getMail())
                .setIssuedAt(new Date())
                .setExpiration(new Date(CommonUtil.getCurrentTimestamp()+EXPIRED))
                .signWith(SignatureAlgorithm.HS256,SECRET).compact();
        token = TOKEN_PREFIX + token;
        return token;
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public static Claims checkJWT(String token) {
        try{
            final Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token.replace(TOKEN_PREFIX,"")).getBody();
            return claims;
        } catch (Exception e) {
            log.error("JWT 解密失败：{}",e.getMessage());
            return null;
        }
    }
}
